package com.dylan.channel.v2;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.StandardCharsets;
import java.util.Iterator;
import java.util.Set;
import java.util.logging.Logger;

public class NettyServer {
    private  static  Logger logger=Logger.getLogger(NettyServer.class.getName());
    public static void main(String[] args) {
        try {
            Selector selector=Selector.open();
            ServerSocketChannel serverSocketChannel=ServerSocketChannel.open();
            serverSocketChannel.configureBlocking(false);
            serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT );
            serverSocketChannel.bind(new InetSocketAddress(8086));
            SingleThreadEventExecutor work=new SingleThreadEventExecutor();
            while (true){
                selector.select();
                Set<SelectionKey> keys = selector.selectedKeys();
                Iterator<SelectionKey> iterator = keys.iterator();
                while (iterator.hasNext()){
                    SelectionKey key = iterator.next();
                    try {
                        iterator.remove();
                        if(key.isAcceptable()){ //如果是连接事件
                            SocketChannel socketChannel = serverSocketChannel.accept();
                            socketChannel.configureBlocking(false);
                            work.register(socketChannel);
                        }
                        if(key.isReadable()){
                            SocketChannel channel = (SocketChannel) key.channel();
                            ByteBuffer buffer = ByteBuffer.allocate(1024);
                            int read = channel.read(buffer);
                            if(read==-1){
                                channel.close();
                                key.cancel();
                                break;
                            }
                            buffer.flip();
                            logger.info("接受到客户端发过来的消息:"+new String(buffer.array(), StandardCharsets.UTF_8));
                        }
                    } catch (IOException e) {
                      e.printStackTrace();
                      key.cancel();
                    }


                }
            }

        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
